package com.jikedaquan.game.jwt.service.impl;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.date.BetweenFormater;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.jikedaquan.game.jwt.entity.Exercise;
import com.jikedaquan.game.jwt.entity.User;
import com.jikedaquan.game.jwt.entity.UserAttr;
import com.jikedaquan.game.jwt.mapper.ExerciseMapper;
import com.jikedaquan.game.jwt.mapper.UserAttrMapper;
import com.jikedaquan.game.jwt.mapper.UserMapper;
import com.jikedaquan.game.jwt.service.ExerciseService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jikedaquan.game.jwt.util.ValueCalc;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.Date;

/**
 * <p>
 * 修炼记录 服务实现类
 * </p>
 *
 * @author jiake
 * @since 2019-10-31
 */
@Service
public class ExerciseServiceImpl extends ServiceImpl<ExerciseMapper, Exercise> implements ExerciseService {
    @Resource
    private UserMapper userMapper;

    @Resource
    private UserAttrMapper userAttrMapper;

    @Transactional
    @Override
    public boolean start(User user) {
        Exercise exercise = getCurrentExercise(user);
        user = userMapper.selectById(user.getId());
        //没有记录或者有结束时间直接修炼
        if (exercise == null || exercise.getEndTime() != null) {
            //事务操作
            int result = 0;
            try {
                //消耗体力操作
                if (user.getTl()-20>0){
                    user.setTl(user.getTl()-20);
                    userMapper.updateById(user);
                    //插入修炼数据
                    Exercise insertData = new Exercise().setUserId(user.getId());
                    result = baseMapper.insert(insertData);
                }else {
                    return false;
                }

            } catch (Exception e) {
//                e.printStackTrace();
                throw new RuntimeException();
            }
            return result == 1;
        } else {
            return false;
        }
    }

    @Override
    public Exercise getCurrentExercise(User user) {
        //获取当前用户最新的一条修炼状态
        QueryWrapper<Exercise> queryWrapper = new QueryWrapper<Exercise>()
                .eq("user_id", user.getId())
                .orderByDesc("start_time").last(" limit 0,1");
        Exercise exercise = baseMapper.selectOne(queryWrapper);
        return exercise;
    }

    @Override
    public String getExerciseStatusStr(Date startTime) {
        StringBuffer statusStr = new StringBuffer();
        //计算出与当前时间的分钟差
        long between = DateUtil.between(startTime, new Date(), DateUnit.MINUTE);
        String str = DateUtil.formatBetween(between*60*1000, BetweenFormater.Level.MINUTE);
        if (between<=5){
            statusStr.append("清神养气(").append(str).append("钟)");
        }else if (between>5&&between<=30){
            statusStr.append("渐入佳境(").append(str).append("钟)");
        }else if(between>30&&between<4*60){
            statusStr.append("略有所获(").append(str).append("钟)");
        }else{
            statusStr.append("修成正果(4小时)");
        }
        return statusStr.toString();
    }

    @Override
    public Exercise stop(User user) {
        //检查是否是正在修炼,没有修炼即无法停止修炼
        user = userMapper.selectById(user.getId());
        UserAttr userAttr = userAttrMapper.selectOne(new QueryWrapper<UserAttr>().eq("user_id",user.getId()));
        Exercise currentExercise = getCurrentExercise(user);
        if (currentExercise==null||currentExercise.getEndTime()!=null){return null;}
        //检查是否足够5分钟，超过5分钟结算
        long between = DateUtil.between(currentExercise.getStartTime(), new Date(), DateUnit.MINUTE);
        if (between<5){
            currentExercise.setExp(0);
            currentExercise.setTechnical(0);
        }else{
            //根据等级和是否有加成计算经验
            //TODO 加成等扩展

            //根据分钟数计算技能点和经验
            if (between>=240){
                Integer exerciseExp = ValueCalc.exerciseExp(user.getLevel(), 240, user.getExcited());
                currentExercise.setExp(exerciseExp);
                currentExercise.setTechnical(240);
            }else{
                Integer exerciseExp = ValueCalc.exerciseExp(user.getLevel(), Convert.toInt(between), user.getExcited());
                currentExercise.setExp(exerciseExp);
                currentExercise.setTechnical(Convert.toInt(between));
            }
        }
        try {
            //经验累加及完成修炼几率
            user.setExp(user.getExp()+currentExercise.getExp());
            currentExercise.setStatus(2);
            userAttrMapper.updateById(userAttr);
            userMapper.updateById(user);
            baseMapper.updateById(currentExercise);
        } catch (Exception e) {
//            e.printStackTrace();
            currentExercise=null;
            throw new RuntimeException();
        }
        return currentExercise;
    }
}
